package com.boboPlanet.comm.filestorage;

import com.alibaba.excel.EasyExcel;
import com.boboPlanet.comm.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Description: TODO 星球 EasyExcel模板
 * @Author: mis_wu
 * @Date: 2023/7/10
 * @Company planet
 **/
@Slf4j
@Component
public class PlanetEasyExcelTemplate {

    private static final String DEFAULT_FILE_NAME_PREFIX = "PlanetExcel";
    private static final String DEFAULT_SHEET_NAME_PREFIX = "PlanetSheet";
    private static final String FILE_SUFFIX = ".xlsx";

    /**
     * EasyExcel下载excel
     * @param fileName 文件名称
     * @param zclass 导出用的模板类，可使用注解定义导出/忽略的字段
     * @param data 数据集合
     * @param sheetName sheet名称
     * @param <T> 参数类型
     */
    public <T>void downloadExcel(String fileName, Class<T> zclass,Collection<Object> data,String sheetName){
        if (data == null){
            throw BusinessException.build("数据列表不能为空,请重新选择");
        }
        if (zclass == null){
            throw BusinessException.build("模板类不能为空,请联系管理员");
        }
        if (StringUtils.isBlank(sheetName)){
            sheetName = DEFAULT_SHEET_NAME_PREFIX + System.currentTimeMillis();
        }
        if (StringUtils.isBlank(fileName)){
            fileName = DEFAULT_FILE_NAME_PREFIX + System.currentTimeMillis() + FILE_SUFFIX;
        }
        int index = fileName.lastIndexOf(FILE_SUFFIX);
        String suffix = fileName.substring(index);
        if (!FILE_SUFFIX.equals(suffix)){
            fileName = fileName + FILE_SUFFIX;
            log.error("downloadExcel error,file name not match,suffix is must [.xlsx]");
        }

        EasyExcel.write(fileName,zclass).sheet(sheetName).doWrite(data);

    }

}
